<?php
# =====================================
# 作者：老曹  QQ:1484743
# 版权声明：本程序为个人原创、开源程序，禁止用于任何违法用途，任何违法用途均与作者无关。
# 仅限学习交流，转载请注明出处。如需商用请联系作者。
# =====================================
require_once __DIR__ . '/../core/db.php';
require_once __DIR__ . '/../core/auth.php';
require_once __DIR__ . '/../core/smart_parser.php';
require_once __DIR__ . '/../core/health_evaluator.php';
header('Content-Type: application/json');
$data = json_decode(file_get_contents('php://input'), true);
if (!isset($data['hostId'], $data['token'], $data['smart_json'], $data['device'], $data['model'], $data['serial'], $data['capacity'])) {
    http_response_code(400);
    echo json_encode(['error' => '参数缺失']);
    exit;
}
$hostId = intval($data['hostId']);
$token = $data['token'];
if (!check_auth($hostId, $token)) {
    http_response_code(403);
    echo json_encode(['error' => '鉴权失败']);
    exit;
}
$db = new DB();
// 1. 硬盘信息入库
$stmt = $db->prepare('SELECT disk_id FROM disks WHERE host_id=? AND serial=?');
$stmt->bind_param('is', $hostId, $data['serial']);
$stmt->execute();
$stmt->bind_result($diskId);
if (!$stmt->fetch()) {
    $stmt->close();
    $stmt2 = $db->prepare('INSERT INTO disks (host_id, device, model, serial, capacity) VALUES (?, ?, ?, ?, ?)');
    $stmt2->bind_param('isssi', $hostId, $data['device'], $data['model'], $data['serial'], $data['capacity']);
    $stmt2->execute();
    $diskId = $db->insert_id();
    $stmt2->close();
}
$stmt->close();
// 2. SMART数据解析与入库
$metrics = parse_smart_data($data['smart_json']);
foreach ($metrics as $metricId => $value) {
    $stmt = $db->prepare('INSERT INTO disk_data (disk_id, metric_id, value) VALUES (?, ?, ?)');
    $stmt->bind_param('iid', $diskId, $metricId, $value);
    $stmt->execute();
    $stmt->close();
}
// 3. 健康度评估
$health = evaluate_health($metrics);
$stmt = $db->prepare('INSERT INTO health_assessments (disk_id, score, status, abnormal_metrics) VALUES (?, ?, ?, ?)');
$abnormal = implode(',', $health['abnormal']);
$stmt->bind_param('iiss', $diskId, $health['score'], $health['status'], $abnormal);
$stmt->execute();
$stmt->close();
$db->close();
echo json_encode(['result' => 'success']); 